<template>

	<view class="setpage">
		<view class="infoitem">
			<text class="leftinfo">头像</text>
			<view class="rightinfo" @click="changeimg">
				<view class="contentbox">
					<image :src="userinfo.avatar?userinfo.avatar:'/static/image/appicon.png'" mode="aspectFill"></image>
				</view>
				<text class="forward"></text>
			</view>
		</view>

		<view class="infoitem">
			<text class="leftinfo">昵称</text>
			<view class="rightinfo">
				<view class="contentbox">{{userinfo.nickname}}</view>
			</view>
		</view>
		<view class="infoitem">
			<text class="leftinfo">性别</text>
			<view class="rightinfo">
				<view class="contentbox">{{sex[userinfo.gender]}}</view>
			</view>
		</view>


		<navigator url="/pages/login/phonelogin?op=bind" class="infoitem">
			<text class="leftinfo">手机号</text>
			<view class="rightinfo">
				<view :class="['contentbox', !userinfo.phone?'font-red':'']">{{isphone}}</view>
				<text class="forward">›</text>
			</view>
		</navigator>

		<!-- <view @click="realnamenavto" class="infoitem">
			<text class="leftinfo">实名认证</text>
			<view class="rightinfo" v-if="!is_realname">
				<view class="contentbox font-red">去实名</view>
				<text class="forward">›</text>
			</view>
			<view class="rightinfo" v-if="is_realname">
				<view class="rzimage">
					<image src="/static/image/rz_icon.png"></image>
					<text style="color: #378aff;">已实名</text>
				</view>
				<text class="forward"></text>
			</view>
		</view> -->


		<view class="infoitem">
			<view class="leftinfo">
				<image src="/static/image/wechat_logo.png" mode="aspectFill"></image>
				<view>微信授权</view>
			</view>
			<view class="rightinfo">
				<view :class="['contentbox',wxbind? '':'font-red']" @click="wxAuth">{{wxbind?"已绑定":"去绑定"}}</view>
				<text class="forward">›</text>
			</view>
		</view>

		<view class="infoitem">
			<view class="leftinfo">
				<image src="/static/image/zhifubao_logo.png" mode="aspectFill"></image>
				<view>支付宝授权</view>
			</view>
			<view class="rightinfo">
				<view :class="['contentbox',alipaybind? '':'font-red']" @click="alilogin">{{alipaybind?"已绑定":"去绑定"}}</view>
				<text class="forward">›</text>
			</view>
		</view>

		<view class="infoitem">
			<view class="leftinfo">
				<image src="/static/image/douyi_logo.png" mode="aspectFill"></image>
				<view>抖音授权</view>
			</view>
			<view class="rightinfo">
				<view :class="['contentbox',dybind? '':'font-red']" @click="tiktokAuth">{{dybind?"已绑定":"去绑定"}}</view>
				<text class="forward">›</text>
			</view>
		</view>
		
		<view class="infoitem">
			<text class="leftinfo">我的邀请人</text>
			<view class="rightinfo">
				<view class="contentbox font-red" v-if="!promote_bind" @tap="visible=true">未绑定</view>
				<view class="contentbox" v-if="promote_bind" @tap="showbind">
					<image :src="userinfo.promote.avatar" mode="aspectFill"></image>
				</view>
				<text class="forward">›</text>
			</view>
		</view>

		<view class="infoitem">
			<text class="leftinfo">开启消息推送</text>
			<view class="rightinfo">
				<view class="contentbox" style="margin: 0;" @click="gotopush">
					<switch disabled="true" color="#378aff" style="transform: scale(0.8);" :checked="messagepush" />
				</view>
			</view>
		</view>

		<navigator url="/pages/setinfo/aboutapp" class="infoitem">
			<text class="leftinfo">关于天天有礼</text>
			<view class="rightinfo">
				<view class="contentbox">v{{version}}</view>
				<text class="forward">›</text>
			</view>
		</navigator>

		<view class="outlogin outbutton" @click="outlogin">退出登陆</view>

		<view style="height: 300rpx;"></view>

		<!--邀请人-->
		<alert modeltitle="填写邀请人" :visible="visible">
			<view class="inputcode">
				<form @submit="formSubmit">
					<input @input="inputcharge" :value="codeinfo" style="border-bottom: 1rpx solid #F1F1F1;" name="code" type="text"
					 maxlength="8" placeholder="输入邀请码" />
					<button formType="submit" type="primary" class="outlogin" style="height: 80rpx;">提交</button>
				</form>
			</view>
		</alert>
		<!--联系客服-->
		<alert modeltitle="注销账号提示" :visible="cancellation">
			<view class="contactus">
				<view class="coop-text">
					<view>此操作一但确认，您的账号【<text style="color: #F43F3B;">{{userinfo.nickname}}</text>】将全部冻结无法使用，请慎重考虑！</view>
				</view>
				<view class="coop-button">
					<view class="cancel" @tap="cancellation=false">取消</view>
					<view class="copywechat" @click="comfir">{{comfirtext}}</view>
				</view>
			</view>
		</alert>

		<!-- <cropper ref="cropper" :aspectRatio="1" @complete="complete" @cancel="cancel" ></cropper> -->
	</view>
</template>

<script>
	/**
	 * 设置中心主页面
	 */
	//引入支付宝登陆云插件
	const PPAliPay = uni.requireNativePlugin('PP-Alipay');
	const Tiktok = uni.requireNativePlugin("Html5app-Tiktok");
	export default {
		data() {
			return {
				canceltime: 10,
				comfirtext: '10s',
				cancellation: false,
				version: '', //应用本版号
				userinfo: '', //用户信息
				isphone: '去绑定',
				alipaybind: false, //是否绑定支付宝
				dybind: false, //是否抖音授权
				wxbind: false, //是否微信授权
				wechatbind: false,
				is_realname: true, //是否实名认证
				promote_bind: false, //是否绑定上级
				visible: false, //显示隐藏alert框
				wechat: 'TianTianYouLi888',
				sex: ['未知', '男', '女'],
				codeinfo: "",
				messagepush: '',
			}
		},
		onNavigationBarButtonTap(e) {
			let _this = this
			if (!this.cancellation) {
				this.cancellation = true
				let cancletime = setInterval(() => {
					this.canceltime--
					this.comfirtext = this.canceltime + 's'
					if (this.canceltime <= 0) {
						clearInterval(cancletime)
						this.comfirtext = '立即注销'
					}
				}, 1000)
			}
			// uni.showModal({ //提醒用户更新
			// 	title: "注销账户提示",
			// 	content: '此操作一但确认，您的账号【'+_this.userinfo.nickname+'】将全部冻结无法使用，请慎重考虑！',
			// 	showCancel: true,
			// 	//confirmText:'前往登陆',
			// 	success: (ret) => {
			// 		console.log(ret)
			// 		//用户点击确认后触发 
			// 		if (ret.confirm) {
			// 			_this.$HttRequest({
			// 				url: '/member/cancellation', 
			// 				param: '',
			// 			}, 'GET', true).then(res => {
			// 				console.log(res)
			// 				if (res.status === 10000) {
			// 					_this.$Expire('账号注销成功')
			// 				} else {
			// 					_this.$ShowMsg(res.message)
			// 				}
			// 			}).catch(error => {
			// 				_this.$ShowMsg('error::'+error)
			// 			})
			// 		}
			// 	}
			// })
		},
		onLoad() {
			//全局订阅事件（多次)
			uni.$on("closewindown", (option) => {
				//关闭alret提示框
				this.visible = option;
				this.cancellation = option;
				this.canceltime = 10;
				this.comfirtext = '10s';
			})
		},

		onShow() {
			//用户没有登陆跳回登陆页
			if (!uni.getStorageSync('dxzk_access_token')) {
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}
			//获取用户信息
			this.userinfo = uni.getStorageSync('user_info');
			//获取应用版本号
			this.version = plus.runtime.version;
			//是否绑定电话
			if (this.userinfo.phone) {
				this.isphone = this.userinfo.phone
			}
			//是否绑定支付宝
			this.alipaybind = this.userinfo.alipay_user_id ? true : false;
			//是否绑定抖音
			this.dybind = this.userinfo.dy_open_id ? true : false;
			//是否微信授权
			this.wxbind = this.userinfo.wx_openid ? true : false;
			console.log(this.wxbind)
			//上级用户信息
			this.promote_bind = this.userinfo.promote.avatar ? true : false;
			//是否实名认证
			this.is_realname = this.userinfo.real_name;

			//检测消息推送是否开启
			this.checkpushopen()
		},
		methods: {
			//消户
			comfir() {
				if(this.canceltime<=0){
					let _this = this
					_this.$HttRequest({
						url: '/member/cancellation',
						param: '',
					}, 'GET', true).then(res => {
						console.log(res)
						if (res.status === 10000) {
							_this.$Expire('账号注销成功')
						} else {
							_this.$ShowMsg(res.message)
						}
					}).catch(error => {
						_this.$ShowMsg('error::' + error)
					})
				}
			},
			//检测消息推送是否开启
			checkpushopen() {
				if (plus.os.name == 'Android') {
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					var NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置  
					if (areNotificationsEnabled) {
						this.messagepush = true
					} else {
						this.messagepush = false
					}
				} else if (plus.os.name == 'iOS') {
					var UIApplication = plus.ios.import("UIApplication");
					var app = UIApplication.sharedApplication();
					var enabledTypes = 0;
					if (app.currentUserNotificationSettings) {
						var settings = app.currentUserNotificationSettings();
						enabledTypes = settings.plusGetAttribute("types");
					} else {
						//针对低版本ios系统    
						enabledTypes = app.enabledRemoteNotificationTypes();
					}
					plus.ios.deleteObject(app);
					if (enabledTypes) {
						this.messagepush = true
					} else {
						this.messagepush = false
					}
				}
			},

			//前往系统设置消息推送
			gotopush() {
				if (plus.os.name == 'Android') {
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					var Intent = plus.android.importClass('android.content.Intent');
					var Build = plus.android.importClass("android.os.Build");
					//android 8.0引导  
					if (Build.VERSION.SDK_INT >= 26) {
						var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
						intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
					} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
						var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
						intent.putExtra("app_package", pkName);
						intent.putExtra("app_uid", uid);
					} else { //(<21)其他--跳转到该应用管理的详情页  
						intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
						var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
						intent.setData(uri);
					}
					main.startActivity(intent)
				} else if (plus.os.name == 'iOS') {
					var UIApplication = plus.ios.import("UIApplication");
					var NSURL = plus.ios.import("NSURL");
					var setting = NSURL.URLWithString("app-settings:");
					var application = UIApplication.sharedApplication();
					application.openURL(setting);
					plus.ios.deleteObject(setting);
					plus.ios.deleteObject(application);
				}
			},

			//微信授权
			wxAuth() {
				let _this = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						_this.$HttRequest({
							url: '/wxpay/authBase',
							param: loginRes.authResult,
						}, 'POST', true).then(res => {
							console.log(res)
							if (res.status === 10000) {
								_this.$changefield('wx_openid', loginRes.authResult.openid)
								_this.wxbind = true;
								_this.$ShowMsg('微信号绑定成功')
							} else {
								_this.$ShowMsg(res.message)
							}
						}).catch(error => {
							_this.$ShowMsg(JSON.stringify(error))
						})
					},
					fail: function(error) {
						console.log(error)
						_this.$ShowMsg('授权失败', 'error')
					}
				})
			},

			//抖音授权
			tiktokAuth() {
				let _this = this;
				if (this.dybind) {
					_this.$ShowMsg('无需重复绑定')
					return
				}
				Tiktok.auth({
					scope: "user_info",
					state: "0022"
				}, ret => {
					// uni.showToast({
					// 	title:  JSON.stringify(ret),
					// 	duration: 2500,
					// 	icon: "none",
					// })
					_this.tip = JSON.stringify(ret);
					console.log(_this.tip);
					if (ret.code == 0) {
						_this.$HttRequest({
							url: '/douyin/authBase',
							param: {
								authCode: ret.authCode
							},
						}, 'POST', true).then(res => {
							console.log(res)
							if (res.status === 10000) {
								_this.$changefield('dy_open_id', res.data)
								_this.dybind = true;
								_this.$ShowMsg('抖音号绑定成功')
							} else {
								_this.$ShowMsg(res.message)
							}
						}).catch(error => {
							_this.$ShowMsg(JSON.stringify(error))

						})
					} else {
						_this.$ShowMsg(ret.msg)
					}
				})
			},

			//强制装换大小写
			inputcharge(e) {
				this.codeinfo = e.detail.value.replace(/[^0-9a-zA-Z]/g, '').toUpperCase();
			},
			//实名认证
			realnamenavto() {
				if (this.is_realname) {
					this.$ShowMsg('无须重复实名！')
					return
				}
				uni.navigateTo({
					url: '/pages/setinfo/realname'
				})
			},
			copywechats() {
				uni.setClipboardData({
					data: this.wechat,
					success() {
						console.log('success');
					}
				});
			},
			showbind() {
				this.$ShowMsg('您已绑定邀请人！');
			},
			//退出
			outlogin() {
				let that = this
				uni.showModal({
					title: '提示',
					content: '您确定退出嘛？',
					success: function(res) {
						if (res.confirm) {
							that.$Expire('成功退出')
						}
					}
				})
				console.log('退出')
			},

			//修改用户头像
			changeimg() {
				return
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(ImageRes) {
						this.$refs.cropper.init(ImageRes);
						// that.$Uploadimg(ImageRes).then((res) => {
						// 	console.log(res);
						// 	let ret = JSON.parse(res);
						// 	console.log(ret)
						// 	if (ret.status === 10000) {
						// 		let imgurl = ret.data;
						// 		that.userinfo.avatar = imgurl;
						// 		//修改用户新
						// 		let userInfo = uni.getStorageSync('user_info');
						// 		userInfo.avatar = imgurl;
						// 		uni.setStorageSync('user_info', userInfo);
						// 		that.$ShowMsg('图片上传成功！')
						// 	} else {
						// 		that.$ShowMsg(ret.message)
						// 	}
						// }).catch((error) => {
						// 	//异常错误
						// 	that.$ShowMsg('statusCode：' + error);
						// });
					}
				})
			},

			complete(e) {
				console.log(e);
			},
			cancel(e) {
				console.log(e);
			},

			//阿里支付宝登陆
			alilogin() {

				if (this.alipaybind) {
					this.$ShowMsg('无须重复绑定！')
					return;
				}
				let that = this;
				that.$HttRequest({
					url: '/login/alipayAuth',
					param: ''
				}).then((res) => {
					if (res.status === 10000) {
						//console.log(res.data);
						PPAliPay.login({
							authInfo: res.data,
							appScheme: 'alipay123456789'
						}, ret => {
							console.log(ret.data);
							if (ret.code == 200) {
								//获取支付宝用户信息
								that.$HttRequest({
									url: '/alipay/authBase',
									param: ret.data,
								}, 'POST').then((res) => {
									console.log(res);
									if (res.status === 10000) {
										//存储支付宝唯一标示符
										console.log(res.data.alipay_user_id);
										if (res.data.alipay_user_id) {
											that.$changefield('alipay_user_id', res.data.alipay_user_id)
											that.alipaybind = true;
										}
										that.$ShowMsg('支付宝绑定成功！')
									} else {
										that.$ShowMsg(res.message)
									}
								}).catch((error) => {
									//异常错误
									that.$ShowMsg('statusCode：' + error.errMsg);
								});
							}
							//result 返回结果 参考 //https://opendocs.alipay.com/open/218/105327
							//{"code":200,"data":{"alipayOpenId":"xx","authCode":"xx","resultCode":"xx","userId":"xxx"},"msg":"登录完成"}
						});
					} else {
						that.$ShowMsg(res.message)
					}
				}).catch((error) => {
					//异常错误
					that.$ShowMsg('statusCode：' + error.errMsg);
				})

			},

			//用户邀请绑定
			formSubmit(e) {
				let code = e.detail.value.code;
				if (!code) {
					this.$ShowMsg('邀请码不能为空！');
					return;
				}
				this.$HttRequest({
					url: '/promote/fillIn',
					param: {
						code: code,
					}
				}, 'POST').then((res) => {
					console.log(res);
					if (res.status === 10000) {
						//更新邀请人信息
						let userInfo = uni.getStorageSync('user_info');
						userInfo.promote = res.data;
						uni.setStorageSync('user_info', userInfo);
						this.userinfo = userInfo;
						//绑定上下级
						this.promote_bind = true;
						this.$ShowMsg('邀请人绑定成功！');
						this.visible = false;
					} else {
						this.$ShowMsg(res.message);
						this.visible = false;
					}
				}).catch((error) => {
					//异常错误
					this.$ShowMsg('statusCode：' + error.errMsg);
				});
			},
			//获取邀请人信息

		}
	}
</script>

<style lang="scss">
	.contactus {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		flex: 1;

		.coop-text {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: flex-start;
			flex-direction: column;

			text {
				margin: 10rpx 0;
			}

			.zhuyi {
				margin-top: 40rpx;
				color: #8b8b8b;
			}
		}

		.coop-button {
			width: 100%;
			display: flex;
			flex: 1;
			align-items: center;
			justify-content: space-around;
			margin: 20rpx 0;

			.cancel {
				display: flex;

				align-items: center;
				justify-content: center;
				width: 170rpx;
				height: 75rpx;
				background-color: #e6e6e6;
				color: #808080;
				border-radius: 30rpx;
			}

			.copywechat {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 240rpx;
				height: 75rpx;
				background-color: $uni-color-primary;
				border-radius: 30rpx;
				color: #fff;
			}
		}

	}

	//邀请码文本框
	.inputcode {
		margin-top: 50rpx;
	}

	.setpage {
		width: 90vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		margin: 0 auto;
		position: relative;

		.copyright {
			font-size: 28rpx;

			position: absolute;
			bottom: 50rpx;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;

			.policy {
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: bold;
				margin-bottom: 20rpx;
				color: $uni-color-primary;

				.line {
					margin: 0 20rpx;
				}
			}

			.smallcopy {
				color: #b0b0b0;
				font-size: 22rpx;
			}
		}

		.infoitem {
			display: flex;
			justify-content: space-between;
			width: 100%;
			height: 100rpx;
			align-items: center;
			border-bottom: 1rpx solid #f4f4f4;
			font-size: 35rpx;
			padding: 5rpx 0;
			color: #333;

			.leftinfo {
				font-size: 28rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				image {
					margin-right: 10rpx;
					width: 50rpx;
					height: 50rpx;
				}
			}

			.rightinfo {
				display: flex;
				width: 40%;
				height: 120rpx;
				font-size: 28rpx;
				color: #9b9b9b;

				.forward {
					display: flex;
					justify-content: center;
					align-items: center;

					font-size: 45rpx;
				}

				.rzimage {
					display: flex;
					justify-content: flex-end;
					align-items: center;
					width: 100%;

					image {
						width: 40rpx;
						height: 40rpx;
						margin: 0 5rpx;
					}
				}

				.contentbox {
					display: flex;
					justify-content: flex-end;
					align-items: center;
					margin: 0 15rpx;
					width: 100%;

					image {
						width: 85rpx;
						height: 85rpx;
						border-radius: 50%;
						border: 1px solid #e6e6e6;
					}
				}

				.font-red {
					color: #FF383A;
				}

			}

		}

		.outlogin {
			color: #fff;
			font-size: 30rpx;
			margin: 20rpx auto;
			margin-top: 30rpx;
			background-color: $uni-color-primary;
			width: 100%;
			display: flex;
			justify-content: center;
			height: 85rpx;
			border-radius: 20rpx;
			align-items: center;

		}

		.outbutton {
			width: 90%;
			height: 90rpx;
			border-radius: 40rpx;
			position: fixed;
			bottom: 20rpx;
			left: 40rpx;
		}

	}
</style>
